package com.yanqu.road.server.logic.thread;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.entity.enums.eChatContentType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eMessageType;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.activity.RankUnionWarProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.entername.EnterNameActivityModule;
import com.yanqu.road.server.gameplayer.module.player.ChatModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PlayerModule;
import com.yanqu.road.server.manger.ForbiddenWordMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.rankunionwar.RankUnionWarMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.WorldMessageMgr;
import com.yanqu.road.server.manger.thirdparty.ThirdPartyMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.pb.WorldMessagePb;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.executor.GeneralTask;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.List;

public class BaseChatTask extends GeneralTask {
    protected GamePlayer player;
    protected int type;
    protected String content;
    protected int contentType;
    protected int activityId;
    protected String banquetId;
    protected long time;
    protected boolean checkContentFirst = false; // 是否先审后发
    protected boolean replaceIllegal = false; // 替换文本
    protected boolean isLocalCheck = false; // 本地敏感词库检测

    private String contentExceptName; //把指定玩家名字排除后用来过屏蔽字
    private String groupParam;
    private boolean showIp;


    public BaseChatTask(GamePlayer player, int type, int contentType, String content, int activityId, String banquetId, long time,
                        boolean checkContentFirst, boolean replaceIllegal, boolean isLocalCheck, List<String> callUserNameList, String groupParam, boolean showIp) {
        super();
        this.player = player;
        this.type = type;
        this.content = content;
        this.contentExceptName = this.content;
        if (null != callUserNameList) {
            for (String userName : callUserNameList) {
                this.contentExceptName = this.contentExceptName.replace(userName, "  ");
            }
        }

        this.contentType = contentType;
        this.activityId = activityId;
        this.banquetId = banquetId;
        this.time = time;
        this.checkContentFirst = checkContentFirst;
        this.replaceIllegal = replaceIllegal;
        this.isLocalCheck = isLocalCheck;
        this.groupParam = groupParam;
        this.showIp = showIp;
    }

    @Override
    public void doRun() {
        WorldMessageProto.WorldChatRespMsg.Builder respMsg = WorldMessageProto.WorldChatRespMsg.newBuilder();
        respMsg.setRet(0);
        player.sendPacket(Protocol.U_WORLD_CHAT, respMsg);

        // 先检查
        WorldMessageProto.WorldMessageTempMsg.Builder msg = WorldMessagePb.parseWorldMessageTempMsg(player.getUserInfo(), type, contentType, content, time, activityId, banquetId);
        // 附加ip信息
        if(showIp){
            if(!StringUtils.isNullOrEmpty(player.getUserInfo().getIpLocation())){
                //msg.setIpLocation(player.getUserInfo().getIpLocation());
                msg.setIpLocation(player.getModule(EnterNameActivityModule.class).getIp_cityName());
            }
        }
        if(!StringUtils.isNullOrEmpty(groupParam)) {
            msg.setExtraParams(groupParam);
        }
        if (player.getUserInfo().getForbiddenSpeakEndTime() > System.currentTimeMillis()) {//被禁言

            if (ForbiddenWordMgr.isForbidden(content) && replaceIllegal) {
                msg.setContent("***");
            }
            player.sendPacket(Protocol.U_WORLD_MESSAGE_SYNC, msg);
            return;
        }

        if (contentType == eChatContentType.Expression.getContentType()) {
            isLocalCheck = false;
        }

        if(type == eMessageType.SpringBanquetOpen.getValue()){
            isLocalCheck = false;
            checkContentFirst = false;
        }

        boolean legal = isLegal();

        if (legal) {
            if (eMessageType.CrossGroupChat.getValue() == type) {
                player.getModule(CurrencyModule.class).removeCurrency(new Property(GameConfig.GAME_ITEM_CROSS_GROUP_CHAT, BigInteger.ONE),
                        eLogMoneyType.System, eLogMoneyType.CrossGroupChat);
            }
            if (eMessageType.CrossGroupUnionRecruit.getValue() == type) {
                //附加商会消息
                CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(player.getUserInfo().getUnionUid());
                if (null != unionInfo) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("flag", unionInfo.getUnionFlag());
                    jsonObject.put("name", unionInfo.getUnionName());
                    jsonObject.put("uid", unionInfo.getUnionUid());
                    jsonObject.put("exp", unionInfo.getExperience());
                    jsonObject.put("serverId", unionInfo.getServerId());
                    jsonObject.put("honerPoint", unionInfo.getHonors());
                    msg.setExtraParams(jsonObject.toJSONString());

                    Property cost = PropertyHelper.parseStringToProperty(GameConfig.GAME_ITEM_CROSS_GROUP_UNION_RECRUIT_CHAT);
                    player.getModule(CurrencyModule.class).removeCurrency(cost,
                            eLogMoneyType.System, eLogMoneyType.CrossGroupUnionRecruitChat);
                } else {//到这里刚好玩家被踢了,低概率
                    return;
                }

            }
            if (eMessageType.ZhaoShangGroupChat.getValue() == type) {
                player.getModule(CurrencyModule.class).removeCurrency(new Property(GameConfig.ZHAO_SHANG_GROUP_CHAT_GAME_ITEM, BigInteger.ONE),
                        eLogMoneyType.System, eLogMoneyType.ZhaoShangGroupChat);
            }
            if (RankUnionWarMgr.getActivityId() != 0 && RankUnionWarMgr.getActivityId() == activityId && !StringUtils.isNullOrEmpty(banquetId)) {
                if (eChatContentType.Expression.getContentType() != contentType) {
                    RankUnionWarProto.CrossRankUnionWarAddBarrageMsg.Builder builder = RankUnionWarProto.CrossRankUnionWarAddBarrageMsg.newBuilder();
                    builder.setActivityId(activityId);
                    builder.setUserId(player.getUserId());
                    builder.setGameNo(Integer.valueOf(banquetId));
                    builder.setContent(msg.getContent());
                    player.sendPacket(CrossProtocol.C2_CROSS_RANKUNIONWAR_ADD_BARRAGE, builder);
                }
            }
            sendChatMsg(player, msg);
        } else {
            illegalDeal(msg);
        }
    }


    protected boolean isLegal() {
        int state = 0;
        state = ThirdPartyMgr.uploadChatDataGetState(player, contentExceptName, (int) (time / 1000), type, activityId, banquetId);
        if (checkContentFirst) {
            // 先审后发
            if (state == 1) {
                // 允许成功
                // 本地检测
                return localCheckLegal();
            }
            return false;
        } else {
            // 本地检测
            return localCheckLegal();
        }
    }


    private void sendChatMsg(GamePlayer player, WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        WorldMessageMgr.addWorldMessage(player, msg);
    }

    public void illegalDeal(WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        // 禁止发送
        ChatModule chatModule = player.getModule(ChatModule.class);
        // 替换文本
        if (replaceIllegal && contentType != eChatContentType.Expression.getContentType()) {
            content = "***";
            msg.setContent("***");
        }
        chatModule.addForbiddenMessage(WorldMessagePb.parseWorldMessageTempMsg(player.getUserInfo(), type, contentType, content, time, activityId, banquetId));

        if (eMessageType.CrossGroupChat.getValue() == type || eMessageType.ZhaoShangGroupChat.getValue() == type || eMessageType.CrossGroupUnionRecruit.getValue() == type) {
            WorldMessageProto.WorldChatRespMsg.Builder respMsg = WorldMessageProto.WorldChatRespMsg.newBuilder();
            respMsg.setRet(GameErrorCode.E_FORBIDDEN_WORD);
            player.sendPacket(Protocol.U_WORLD_CHAT, respMsg);
        } else {
            player.sendPacket(Protocol.U_WORLD_MESSAGE_SYNC, msg);
        }
    }

    /**
     * 本地检查
     */
    public boolean localCheckLegal() {
        int channelId = ServerListMgr.getChannelId(GameServer.getInstance().getServerId());
        if (isLocalCheck && eChannelType.MainLand.getValue() != channelId && ForbiddenWordMgr.isForbidden(content)) {
            return false;
        }
        return true;
    }
}
